package edu.cicese.alz.swing;

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 25/06/12
 * Time: 07:36 PM
 */
public class IntegerDocumentFilter extends DocumentFilter {

	JTextField textField;

	public IntegerDocumentFilter(JTextField textField) {
		this.textField = textField;
	}

	@Override
	public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException {
		try {
			int number = Integer.parseInt(string);

			Integer.valueOf(textField.getText().substring(0, offset) + string + textField.getText().substring(offset));

			if (offset != 0 || (offset == 0 && number != 0)) {
				super.insertString(fb, offset, string, attr);
			}
		} catch (NumberFormatException nfe) {
			/* ignored */
		}
	}

	@Override
	public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException {
		try {
			int number = Integer.parseInt(string);

			Integer.valueOf(textField.getText().substring(0, offset) + string + textField.getText().substring(offset));

			if (offset != 0 || (offset == 0 && number != 0)) {
				super.replace(fb, offset, length, string, attrs);
			}
		} catch (NumberFormatException nfe) {
			if (string.equals("")) {
				super.replace(fb, offset, length, string, attrs);
			}
		}
	}
}
